package com.fht.spring_boot_study.filter;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@WebFilter(filterName = "parameterFilter",urlPatterns = "/*")
public class ParagramFilter implements Filter {
    private final static Logger LOGGER= LoggerFactory.getLogger(ParagramFilter.class);
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
       LOGGER.debug("====init filter====");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        LOGGER.debug("====doFilter====");
        HttpServletRequest httpRequest=(HttpServletRequest)servletRequest;
        HttpServletResponse httpResponse=(HttpServletResponse) servletResponse;
//        Map<String,String[]> paramsMap=httpRequest.getParameterMap();
//        paramsMap.put("aaa",new String[]{"eeeee"});
        HttpServletRequest requestWrapper=
                new HttpServletRequestWrapper(httpRequest){
                    @Override
                    public String getParameter(String name) {
                        String value=super.getParameter(name);
                        if(StringUtils.isBlank(value)){
                            return "";
                        }else {
                            return value.replaceAll("fuck","***");
                        }
                    }

                    @Override
                    public String[] getParameterValues(String name) {
                        String[] values=super.getParameterValues(name);
                        List<String> temp=new ArrayList<>();
                        for (String value:values){
                            temp.add(value.replaceAll("fuck","***"));
//                            value=value.replaceAll("fuck","***");
                        }
                        return temp.toArray(new String[temp.size()]);
                    }
                };
        filterChain.doFilter(requestWrapper,httpResponse);
    }

    @Override
    public void destroy() {
        LOGGER.debug("====destroy filter====");
    }
}
